package xamap

import (
	"encoding/json"

	"gitee.com/xiaoyutab/xgotool/https"
	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xnum"
	"gitee.com/xiaoyutab/xgotool/xstring"
)

// 转换成为的结构体
type IpInfo struct {
	Province  string     `json:"province"`
	City      string     `json:"city"`
	Adcode    int        `json:"adcode"`
	Rectangle []xnum.GPS `json:"rectangle"`
}

// IP地址转地图中的详情信息
//
//	ip	待查询的IPv4地址
func Ip2info(ip string) (*IpInfo, error) {
	type ret_info struct {
		Status    json.Number `json:"status"`
		Info      string      `json:"info"`
		Infocode  json.Number `json:"infocode"`
		Province  string      `json:"province"`
		City      string      `json:"city"`
		Adcode    json.Number `json:"adcode"`
		Rectangle string      `json:"rectangle"`
	}
	inf := ret_info{}
	err := https.Get(geturl("ip"), params(map[string]string{
		"ip": ip,
	}), map[string]string{}).Json(&inf)
	if err != nil {
		return nil, xlog.EE("高德地图IP详情接口请求失败", err)
	}
	// infocode判定
	err = infocode(inf.Infocode)
	if err != nil {
		return nil, err
	}
	return &IpInfo{
		Province:  inf.Province,
		City:      inf.City,
		Adcode:    xstring.JInt(inf.Adcode),
		Rectangle: S2GPSAll(inf.Rectangle),
	}, nil
}
